#include "bwrD.h"

#include <algorithm>
#include <iostream>

#define SIZE 256

using namespace std;

int bwt_algoritmoD(unsigned char* S,unsigned int N,unsigned char* L,unsigned int I){
    
    int *C, *P;
    unsigned int i=0;
    C = new int[SIZE];
    P = new int[N];
    
    //cout << "bwtD - a transformar L: " << L << " con indice " << I << " Y N: "<< N << endl;
    
    //Inicializar C
    for (i=0; i<SIZE; ++i)
    C[i] = 0;
    
//    cout << "bwtD - inicializo C: ";
//    //for para imprimir C (sacar despues)
//    for (i=0;i<SIZE;i++) cout << C[i];
//    cout << endl;
//    
    for (i=0; i<N; ++i)
    {
        P[i] = C[L[i]];
        C[L[i]]++;
    }
    
//    cout << "bwtD - P: " ;
//    for (i=0;i<N;i++) cout << P[i];
//    cout << endl;
//    
//    cout << "bwtD - C: ";
//    //for para imprimir C (sacar despues)
//    for (i=0;i<SIZE;i++) cout << C[i];
//    cout << endl;
    
    int sum = 0;
    for (int ch = 0; ch<SIZE; ++ch)
    {
        sum += C[ch];
        C[ch] = sum-C[ch];
    }
    
//    cout << "bwtD - C ";
//    //for para imprimir C (sacar despues)
//    for (i=0;i<SIZE;i++) cout << C[i];
//    cout << endl;
    
    i = I;
    for (int j=N-1; j>=0; --j)
    {
        S[j] = L[i];
        //cout << "bwtD - S[" << j <<"] va siendo " << S[j] << endl;
        i = P[i] + C[L[i]];      
    }
    delete[] C;
    delete[] P;
    S[N]='\0';// agrego el fin de caracter para ver bien cuando imprimo        
    //cout << "bwtD - tengo S final: " << S << endl;
    
    
    return 0;
    
}
